#!/usr/bin/env python
# -*- coding:utf-8 -*-
import re,json
from scriptd.tasks import Task
import logging
logger = logging.getLogger('django')
def Re(res,total,id = "1"):
    if id == "1":
        data = re.findall(str(res),total)
    if id == "2":
        data = re.findall(str(res),total,re.S)
    return data
class Hitachi():
    def __init__(self,data):
        self.data = data
    def portdata(self):
        data = Re(r"(\d\w),\w+,\w+,\d+,\w+,Point to Point,\w+,(\S{16}),(\S+),",self.data,"2")
        return data
    def host(self):
        data = Re(r"(\d\w),(\S+),\d+,,(\w{16}),,\d+,(\w+-\w+)",self.data,"2")
        return data
    def lundata(self):
        data = Re("\d\w,(\S+),\d+,,\w+,(..:..:..)",self.data,"2")
        dataxinxi = Re(r"(..:..:..),,OPEN-V,([Basic|Dynamic Provisioning]+),\w+,(\d+),(\d+).\d+,(\d+),.*?,,,,.*?,(\w+)!*,,,",self.data,"2")
        return [data,dataxinxi]
    def hdisk(self):
        #('HDD16-15', '600GB', 'GB', 'GB', '', 'RAID1')
        data = Re("(\d+-\d+),\S+,\S+,(HDD\d+-\d+).*?(\d+((GB)|(TB))).*?(RAID\d+)", self.data, "2")
        #('Spare Drive', '', 'Spare Drive', 'HDD00-23', '600GB', 'GB', 'GB', '')
        data2 = Re("((Free\sDrive)|(Spare\sDrive)).*?(HDD\d+-\d+).*?(\d+((GB)|(TB)))", self.data, "2")

        return [data,data2]
from scriptd.towwn import WWn
from san.models import Storage,Wwn
from storagedata import models
#传送存储ID号码及文本信息
def hitachi_to_data(id,text):
    hitachiscipit = Hitachi(text)
    #端口的数据
    portdata = hitachiscipit.portdata()
    task = Task()
    task.start(str("日立存储" + id + "-" + "开始刷新数据"))
    for i in portdata:
        if not models.STPORT.objects.filter(storage_id = id,portname = i[2] + "-" +i[0]):
            pdata = {
                "portname": i[2] + "-" +i[0],
                "storage_id":id,
            }
            obj = models.STPORT.objects.create(**pdata)
            wwn = WWn(i[1])
            try:
                objwwn = Wwn.objects.update_or_create(wwn=wwn)
                objwwn[0].storage_wwn_id = id
                objwwn[0].STport_id = obj.id
                objwwn[0].wwnname = i
                objwwn[0].save()
            except Exception as e:
                obj.delete()
                print(e)
    logger.info("rili-" + id + "=port_finish")
    #LUN
    lun = hitachiscipit.lundata()
    for i in lun[1]:
        data = {
            "lunpname":i[0],
            "lunsize": str(round(int(i[3])/1024,1)),
            "luntype": i[1],
            "storage_id": id,
            "Notes":i[5],
        }
        objlun = models.STLUN.objects.filter(storage_id=id,lunpname=i[0])
        if not objlun:
            obj = models.STLUN.objects.create(**data)
        else:
            objlun[0].lunsize =str(round(int(i[3])/1024,1))
            objlun[0].luntype =i[1]
            objlun[0].Notes =i[5]
            objlun[0].save()
    logger.info("rili-" + id + "=lun_finish")
    # #主机
    print("lun_finish")
    hostdata = hitachiscipit.host()
    models.STHOST.objects.filter(storage_id=id).delete()
    for i in hostdata:
        data = {
                    "hostname": i[1],
                    "storage_id": id,
                    "Notes":str(str(i[3]) + "-" + str(i[0])),
                }
        obj = models.STHOST.objects.create(**data)
        wwn = WWn(i[2])
        try:
            objhostwwn = Wwn.objects.update_or_create(wwn=wwn)
            objhostwwn[0].storage_wwn_id = id
            objhostwwn[0].SThost.add(obj)
            objhostwwn[0].save()
        except Exception as e:
            obj.delete()
            print(e)
    logger.info("rili-" + id + "=host_finish")
    print("host_finish")
#     # 聚合组
    lunmap = lun[0]
    host = []
    for i in lunmap:
        host.append(i[0])
    host = list(set(host))

    for i in host:
        data = {
            "mapname": i,
            "storage_id": id,
        }
        obj = models.STMAP.objects.update_or_create(mapname=i,storage_id=id)
        obj[0].manylun.clear()
        obj[0].manyhost.clear()
        for z in lun[0]:
            if i == z[0]:
                obj[0].manylun.add(*(models.STLUN.objects.filter(lunpname=z[1], storage_id=id)))

        obj[0].manyhost.add(*(models.STHOST.objects.filter(hostname= i, storage_id=id)))
    logger.info("rili-" + id + "=map_finish")
    usedisk,freedisk = hitachiscipit.hdisk()
    print("disk_finish")
    #创建stmap内的Notes的内容
    obj = models.STMAP.objects.filter(storage_id=id)
    for i in obj:
        k = i.mapname
        obj2 = models.STHOST.objects.filter(hostname=k)
        num = []
        for zz in obj2:
            num.append(zz.Notes)
        if num:
            num2 = str(set(num))
            i.Notes = num2
            i.save()
    for d in usedisk:
        data = {
            "diskslot": d[1],
            "disksize": d[2],
            "datatype": d[6],
            "status": "use",
            "diskstatus": "online",
            "disknote": d[0],
            "storage_id": id,
        }
        from storagedata.models import DISK
        obj =  DISK.objects.filter(storage_id = id,diskslot = d[1]).first()
        if not obj:
            obj = DISK.objects.create(**data)
        else:
            obj.disksize = d[2]
            obj.datatype = d[6]
            obj.disknote = d[0]
            obj.save()
    logger.info("rili-" + id + "=map_notes_finish")
    for f in freedisk:
        data = {
            "diskslot": f[3],
            "disksize": f[4],
            "diskstatus": "online",
            "status": f[0],
            "storage_id": id,
        }
        from storagedata.models import DISK
        obj = DISK.objects.filter(storage_id=id, diskslot=f[3]).first()
        if not obj:
            obj = DISK.objects.create(**data)
        else:
            obj.disksize = f[4]
            obj.status =  f[0]
            obj.save()
    logger.info("rili-" + id + "=finish")
    task.end()